/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.oop.example.work.esport;

import com.oop.example.xml.Block;
import com.oop.example.xml.ObjectFactory;
import javax.xml.bind.JAXB;

/**
 *
 * @author -
 */
public class TextUtils {

    private static ObjectFactory factory = new ObjectFactory();
    private static String ib = "<i>";
    private static String ie = "</i>";
    private static String bb = "<b>";
    private static String be = "</b>";

    public static void main(String[] args) {
        String tst = "<i>s</i> dfsdf <i>sd</i> <b>sd</b> sdfsdfs <i>sdfsdfsdfsdfsdf</i> retwertwertewrt <b>sdfsdfsdf</b>";
        Block italicBold = getItalicBold(tst);
        JAXB.marshal(italicBold, System.out);
    }

    public static Block getItalicBold(String txt) {
        Block block = factory.createBlock();
        String src = txt;
        src = src
                .replace("<h1>", "")
                .replace("</h1>", "");


        while ((src.contains(ib) && src.contains(ie)) || (src.contains(bb) && src.contains(be))) {
            int iib = src.indexOf(ib);
            int ibb = src.indexOf(bb);

            if (iib >= 0 && ibb >= 0) {
                if (iib < ibb) {
                    src = insertItalic(block, src);
                } else {
                    src = insertBold(block, src);
                }
            } else if (iib >= 0) {
                src = insertItalic(block, src);
            } else if (ibb >= 0) {
                src = insertBold(block, src);
            }
        }
        block.setValue(src);
        return block;
    }

    private static String insertItalic(Block block, String src) {
        int b = src.indexOf(ib);
        int e = src.indexOf(ie) - ib.length();
        String pos = "" + b + ((e - b == 1) ? "" : ("-" + e));
        src = src.replaceFirst(ib, "").replaceFirst(ie, "");
        String italic = block.getItalic();
        if (italic == null) {
            italic = "";
        }
        if (italic.isEmpty()) {
            italic = pos;
        } else {
            italic = italic + ";" + pos;
        }
        block.setItalic(italic);
        return src;
    }

    private static String insertBold(Block block, String src) {
        int b = src.indexOf(bb);
        int e = src.indexOf(be) - bb.length();
        String pos = "" + b + ((e - b == 1) ? "" : ("-" + e));
        src = src.replaceFirst(bb, "").replaceFirst(be, "");
        String bold = block.getBold();
        if (bold == null) {
            bold = "";
        }
        if (bold.isEmpty()) {
            bold = pos;
        } else {
            bold = bold +  ";" + pos;
        }
        block.setBold(bold);
        return src;
    }
}
